package com.yu.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yu.crm.domain.pojo.CrmBuilding;
import com.yu.crm.domain.pojo.CrmDepartmentMember;
import com.yu.crm.domain.pojo.CrmUser;
import com.yu.crm.domain.response.BuildingRep;
import com.yu.crm.mapper.CrmBuildingMapper;
import com.yu.crm.service.CrmAreaService;
import com.yu.crm.service.CrmDepartmentMemberService;
import com.yu.crm.service.CrmUserService;
import com.yxzz.common.config.UserCacheManager;
import com.yxzz.common.exception.GeneralException;
import com.yxzz.common.helper.DataHelpers;
import com.yxzz.common.helper.valid.ValidatorHelpers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 后台楼栋管理表 服务实现类
 * </p>
 *
 * @author ct
 * @since 2019-08-15
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class CrmBuildingService extends ServiceImpl<CrmBuildingMapper, CrmBuilding>{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    UserCacheManager userCacheManager;
    @Autowired
    CrmAreaService crmAreaService;
    @Autowired
    CrmDepartmentMemberService crmDepartmentMemberService;
    @Autowired
    CrmUserService crmUserService;


    /**
     * 新增或修改楼栋信息
     * @param crmBuilding
     */
    public void addOrUpdate(CrmBuilding crmBuilding){
        try {
            String userId = userCacheManager.getCurrentUser().getUserId();

            //获取登陆用户信息
            //BackUser backUser = backUserService.infoByUserLoginId(userId);
            if(DataHelpers.isNotEmpty(crmBuilding.getId())){
                //修改
                crmBuilding.setGmtModified(LocalDateTime.now());
                crmBuilding.setUpdateUserId(userId);

                ValidatorHelpers.validateDataSave(baseMapper.updateById(crmBuilding));
            }else{
                //新增
                crmBuilding.setGmtCreate(LocalDateTime.now());
                crmBuilding.setCreateUserId(userId);
                //crmBuilding.setTabId(backUser.getTabId());

                ValidatorHelpers.validateDataSave(baseMapper.insert(crmBuilding));
            }

            if(DataHelpers.isNotEmptyString(crmBuilding.getBuildingAreaName())){
                crmAreaService.addCrmArea(crmBuilding.getBuildingAreaName());
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
            throw new GeneralException("操作失败");
        }
    }

    /**
     * 通过条件查询分页楼梯信息
     * @param page
     * @param condition 查询条件 (模糊查询  楼栋区域名称，楼栋名称，备注 )
     * @return
     */
    public IPage<CrmBuilding> page(Page<CrmBuilding> page,String condition){
        try {
            String userId = userCacheManager.getCurrentUser().getUserId();

            //获取登陆用户信息
            //BackUser backUser = backUserService.infoByUserLoginId(userId);
            QueryWrapper<CrmBuilding> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("cb.is_deleted",0);
            //queryWrapper.eq("cb.tab_id",backUser.getTabId());
            if(DataHelpers.isNotEmptyString(condition)){
                queryWrapper.and(i->i.like("cb.building_area_name",condition)
                        .or().like("cb.building_name",condition)
                        .or().like("cb.remark",condition)
                        .or().like("cam.park_area_name",condition)
                );
            }
            queryWrapper.orderByDesc("gmt_create");
            //return baseMapper.selectPage(page,queryWrapper);
            return baseMapper.getPage(page,queryWrapper);
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
            throw new GeneralException("操作失败");
        }
    }

    /**
     * 删除楼梯信息,软删除
     * @param id 楼梯编号
     */
    public void deleteById(Long id){
        try {
            String userId = userCacheManager.getCurrentUser().getUserId();
            CrmBuilding crmBuilding = baseMapper.selectById(id);
            if(DataHelpers.isNotEmpty(crmBuilding)){
                crmBuilding.setGmtModified(LocalDateTime.now());
                crmBuilding.setUpdateUserId(userId);
                crmBuilding.setIsDeleted(1);

                ValidatorHelpers.validateDataSave(baseMapper.updateById(crmBuilding));
                //通过 楼栋区域名称和楼栋名称软删除数据
                //crmUserAddressService.updateByDelete(crmBuilding.getBuildingAreaName(),crmBuilding.getBuildingName());
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
            throw new GeneralException("操作失败");
        }
    }

    /**
     * 通过区域名称查询楼栋名称
     * @param areaName
     * @param type 类型 不为空是企业微信调用
     * @return
     */
    public List<String> listByBuildingName(String areaName,Integer type){
        try {
            String userId = userCacheManager.getCurrentUser().getUserId();
            List<String> list=new ArrayList<>();

            if(DataHelpers.isNotInteger(type)){
                //获取登陆用户信息
                CrmDepartmentMember crmDepartmentMember = crmDepartmentMemberService.infoByUserId(userId);
                if(DataHelpers.isNotEmpty(crmDepartmentMember)){
                    return baseMapper.listByBuildingName(areaName,1);
                }
            }else{
                //获取登陆用户信息
                CrmUser backUser = crmUserService.getByUserId(userId);
                if(DataHelpers.isNotEmpty(backUser)){
                    return baseMapper.listByBuildingName(areaName,1);
                }
            }
            return list;
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
            throw new GeneralException("操作失败");
        }
    }

    /**
     * 查询当前用户所在所有 区域名称
     * @param type 类型 不为空是企业微信调用
     * @return
     */
    public List<String> listByBuildingAreaName(Integer type){
        try {
            String userId = userCacheManager.getCurrentUser().getUserId();
            List<String> list=new ArrayList<>();
            if(DataHelpers.isNotInteger(type)){
                //获取登陆用户信息
                CrmDepartmentMember crmOrgMember=crmDepartmentMemberService.infoByUserId(userId);
                if(DataHelpers.isNotEmpty(crmOrgMember)){
                    return baseMapper.listByBuildingAreaName(1);
                }
            }else{
                //获取登陆用户信息
                CrmUser backUser = crmUserService.getByUserId(userId);
                if(DataHelpers.isNotEmpty(backUser)){
                    return baseMapper.listByBuildingAreaName(1);
                }
            }
            return list;
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
            throw new GeneralException("操作失败");
        }
    }

    /**
     * 通过区域名称和楼栋名称查询楼层名称
     * @param areaName 区域名称
     * @param buildingName 楼栋名称
     * @param type 类型 不为空是企业微信调用
     * @return
     */
    public List<String> listByBuildingFloorName(String areaName,String buildingName,Integer type){
        try {
            String userId = userCacheManager.getCurrentUser().getUserId();
            List<String> list=new ArrayList<>();

            if(DataHelpers.isNotInteger(type)){
                //获取登陆用户信息
                CrmDepartmentMember crmOrgMember=crmDepartmentMemberService.infoByUserId(userId);
                if(DataHelpers.isNotEmpty(crmOrgMember)){
                    return baseMapper.listByBuildingFloorName(areaName,buildingName,1);
                }
            }else{
                //获取登陆用户信息
                CrmUser backUser = crmUserService.getByUserId(userId);
                if(DataHelpers.isNotEmpty(backUser)){
                    return baseMapper.listByBuildingFloorName(areaName,buildingName,1);
                }
            }
            return list;
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
            throw new GeneralException("操作失败");
        }
    }

    /**
     * 通过楼栋区域名称和楼栋名称查询详情
     * @param buildingAreaName  楼栋区域名称
     * @param buildingName  楼栋名称
     * @return
     */
    public CrmBuilding infoByAreaNameOrBuildingName(String buildingAreaName,String buildingName,Integer tabId){
        try {
            QueryWrapper<CrmBuilding> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("building_area_name",buildingAreaName);
            queryWrapper.eq("building_name",buildingName);
            queryWrapper.eq("tab_id",tabId);
            queryWrapper.eq("tab_id",tabId);
            queryWrapper.eq("is_deleted",0);
            return baseMapper.selectOne(queryWrapper);
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
            throw new GeneralException("操作失败");
        }
    }

    public List<BuildingRep> listBuilding(Integer type) {
        try {
            String userId = userCacheManager.getCurrentUser().getUserId();
            List<BuildingRep> list=new ArrayList<>();
            if(DataHelpers.isNotInteger(type)){
                //获取登陆用户信息
                CrmDepartmentMember crmOrgMember=crmDepartmentMemberService.infoByUserId(userId);
                if(DataHelpers.isNotEmpty(crmOrgMember)){
                    return baseMapper.listBuilding(1);
                }
            }else{
                //获取登陆用户信息
                CrmUser backUser = crmUserService.getByUserId(userId);
                if(DataHelpers.isNotEmpty(backUser)){
                    return baseMapper.listBuilding(1);
                }
            }
            return list;
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
            throw new GeneralException("操作失败");
        }
    }

    public BuildingRep listAreaManageById(Long id) {
        return baseMapper.listAreaManageById(id);
    }


    public List<BuildingRep> listBuildingByAreaManageId(Long areaManageId) {
        return baseMapper.listBuildingByAreaManageId(areaManageId);
    }
}
